package ar.edu.itba.bundundu;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.edu.itba.bundundu.dao.UserDao;
import ar.edu.itba.bundundu.domain.BundunduEvent;
import ar.edu.itba.bundundu.domain.UserIds;

import com.google.gdata.client.Query;
import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.calendar.AccessLevelProperty;
import com.google.gdata.data.calendar.CalendarAclRole;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.calendar.CalendarFeed;
import com.google.gdata.data.calendar.SelectedProperty;

@SuppressWarnings("serial")
public class CalendarServlet extends HttpServlet {

	  @Override
	  public void doGet(HttpServletRequest req, HttpServletResponse resp)
	      throws ServletException, IOException {
	    doPost(req, resp);
	  }

	  @Override
	  public void doPost(HttpServletRequest req, HttpServletResponse resp)
	      throws ServletException, IOException {
	    RequestDispatcher dispatcher;
	    dispatcher = getServletContext().getRequestDispatcher("/calendar.jsp");
	    
	    Date date;
	    String str=req.getParameter("date");
	    
	   if(str==null){
	    	date= new Date();
	    }else{
	    	Long time= Long.valueOf(str);
	    	date= new Date(time);
	    }
	   
	    
	    /****** Make the calendar ******/
	    
	    Calendar startCal= Calendar.getInstance();
	    Calendar endCal= Calendar.getInstance();
	    startCal.setTime(date);
	    
	    startCal.set(Calendar.DAY_OF_MONTH, 1);
	    req.setAttribute("month", startCal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault())+ " " + startCal.get(Calendar.YEAR));
	    
	    startCal.add(Calendar.MONTH, 1);
	    req.setAttribute("next_month", startCal.getTimeInMillis());
	    
	    startCal.add(Calendar.MONTH, -2);
	    req.setAttribute("prev_month", startCal.getTimeInMillis());
	 
	    int days_last = startCal.getActualMaximum(Calendar.DAY_OF_MONTH);//days of the month
	    startCal.add(Calendar.MONTH, 1);
	    
	    
	    int days = startCal.getActualMaximum(Calendar.DAY_OF_MONTH);//days of the month
	    int first = startCal.get(Calendar.DAY_OF_WEEK);
	    
	    endCal.setTime(date);
	    endCal.set(Calendar.DAY_OF_MONTH, days);
	    //Habria q setear la hora tambien
	    
	    req.setAttribute("days", days);
	    req.setAttribute("first", first);
	    req.setAttribute("days_last", days_last);
	    /********************************/
	    

	    try {
			Long uid= Long.valueOf(req.getParameter("fb_sig_user"));
			
			  // levantar de la base el token para google calendar
			UserIds user = UserDao.getUser(uid);
			String sessionToken = user.getToken();

			List<BundunduEvent> allEvents= new ArrayList<BundunduEvent>();
			
			CalendarService calendarService = new CalendarService("exampleCo-exampleApp-1");
			calendarService.setAuthSubToken(sessionToken, null);//http://www.google.com/calendar/feeds/default/allcalendars/full
			CalendarFeed calendarFeed =	calendarService.getFeed(new URL ("http://www.google.com/calendar/feeds/default/allcalendars/full"), CalendarFeed.class);
			//http://www.google.com/calendar/feeds/default/owncalendars/full
			String url="http://www.google.com/calendar/feeds/";
			URL feedUrl;
			
			
			
			for (CalendarEntry calEntry : calendarFeed.getEntries()) {
			  if( ! calEntry.getAccessLevel().equals(AccessLevelProperty.FREEBUSY)){
  			  
  				feedUrl = new URL(url+ calEntry.getId().substring(calEntry.getId().lastIndexOf("/")+1, calEntry.getId().length())+ "/private/full");
  			
  				CalendarQuery myQuery = new CalendarQuery(feedUrl);
  				
  				myQuery.setMinimumStartTime(new DateTime(startCal.getTime()));
  				myQuery.setMaximumStartTime(new DateTime(endCal.getTime()));
  			
  				CalendarService myService = new CalendarService("exampleCo-exampleApp-1");
  				myService.setAuthSubToken(sessionToken, null);
  								
  				myQuery.addCustomParameter(new Query.CustomParameter("orderby", "starttime"));
  				myQuery.addCustomParameter(new Query.CustomParameter("sortorder", "ascending"));
  				myQuery.addCustomParameter(new Query.CustomParameter("singleevents", "true"));
  
  				// Send the request and receive the response:
  				CalendarEventFeed resultFeed = myService.query(myQuery,	CalendarEventFeed.class);
  				
  				boolean selected= calEntry.getSelected().equals(SelectedProperty.TRUE);
  				int i=1;
  				for (CalendarEventEntry cal: resultFeed.getEntries()) {
  					BundunduEvent event= new BundunduEvent(cal, calEntry.getColor().getValue(), calEntry.getId()+ i);
  					event.setSelect(selected);
  					allEvents.add(event);
  					i++;
  				}
			  }
			}
			
			req.setAttribute("calendars", calendarFeed.getEntries()); /* Le paso los calendarios */
			req.setAttribute("events", allEvents); /* Le paso todos los eventos */
			
			dispatcher.forward(req, resp);
		} catch (Exception e) {
			req.setAttribute("err", e.getMessage());
		}
		 
		 
		 dispatcher.forward(req, resp);
	  }

	  //http://www.google.com/calendar/feeds/52egn4aul7jsslh81vhkg1i7rs%40group.calendar.google.com/private/full
	  public static int getDayEvent(CalendarEventEntry eventEntry){
		  DateTime date= eventEntry.getTimes().get(0).getStartTime();
		  Calendar calendar= Calendar.getInstance();
		  
		  calendar.setTimeInMillis(date.getValue());
		  
		  return calendar.get(Calendar.DATE);
		  
	  }
	  
	  public static BundunduEvent getEntry(List<BundunduEvent> events, int day){
		  BundunduEvent event= null;
		  int eventDay;
		  
		  for(int i=0; i<events.size(); i++){
			  eventDay=getDayEvent(events.get(i).getEventEntry());
			  if(eventDay==day){
				  event= events.get(i);
				  events.remove(i);
				  break;
			  }
		  }
		  
		  return event;
	  }
	  
	  
	}